#!/usr/bin/env node

/**
 * Rule Converter Tool
 * 
 * Converts human-readable Markdown documentation to machine-readable YAML rules.
 * This tool is used in the CI/CD pipeline to automatically update AI rules
 * when developers modify the human guides.
 */

const fs = require('fs');
const path = require('path');
const marked = require('marked');
const yaml = require('js-yaml');
const glob = require('glob');

// Configuration
const CONFIG = {
  sourcePath: path.resolve(__dirname, '../../config/human-guides/'),
  targetPath: path.resolve(__dirname, '../../config/ai-rules/global/'),
  mappings: {
    'code-style.md': 'code-style.yml',
    'design-patterns.md': 'design-patterns.yml'
  }
};

/**
 * Parse markdown content and convert to structured data
 * @param {string} markdown - Content of markdown file
 * @returns {Object} Structured data extracted from markdown
 */
function parseMarkdown(markdown) {
  const tokens = marked.lexer(markdown);
  const result = {
    rules: []
  };
  
  let currentRule = null;
  let currentSection = null;
  
  tokens.forEach(token => {
    if (token.type === 'heading') {
      if (token.depth === 2) {
        // Level 2 heading indicates a new section
        currentSection = token.text.toLowerCase().replace(/\s+/g, '_');
      } else if (token.depth === 3) {
        // Level 3 heading indicates a new rule
        currentRule = {
          type: token.text.toLowerCase().replace(/\s+/g, '_'),
          description: ''
        };
        result.rules.push(currentRule);
      }
    } else if (token.type === 'paragraph' && currentRule) {
      // Add description to current rule
      currentRule.description += token.text;
    } else if (token.type === 'list' && currentRule) {
      // Process list items for current rule
      const items = token.items.map(item => item.text);
      
      if (currentRule.items) {
        currentRule.items = currentRule.items.concat(items);
      } else {
        currentRule.items = items;
      }
    } else if (token.type === 'code' && currentRule) {
      // Process code example
      try {
        const example = JSON.parse(token.text);
        currentRule.example = example;
      } catch (e) {
        currentRule.example = token.text;
      }
    }
  });
  
  return result;
}

/**
 * Convert parsed data to YAML format
 * @param {Object} data - Structured data from markdown
 * @returns {string} YAML representation
 */
function convertToYaml(data) {
  return yaml.dump(data, {
    indent: 2,
    lineWidth: 100,
    noRefs: true
  });
}

/**
 * Process a single file
 * @param {string} sourcePath - Path to source markdown file
 * @param {string} targetPath - Path to target YAML file
 */
function processFile(sourcePath, targetPath) {
  console.log(`Processing ${sourcePath} -> ${targetPath}`);
  
  try {
    const markdown = fs.readFileSync(sourcePath, 'utf8');
    const parsedData = parseMarkdown(markdown);
    const yamlContent = convertToYaml(parsedData);
    
    // Create directories if they don't exist
    const targetDir = path.dirname(targetPath);
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true });
    }
    
    fs.writeFileSync(targetPath, yamlContent, 'utf8');
    console.log(`Successfully converted ${sourcePath}`);
  } catch (error) {
    console.error(`Error processing ${sourcePath}:`, error);
    process.exit(1);
  }
}

/**
 * Main function
 */
function main() {
  // Process each mapping
  for (const [sourceFile, targetFile] of Object.entries(CONFIG.mappings)) {
    const sourcePath = path.join(CONFIG.sourcePath, sourceFile);
    const targetPath = path.join(CONFIG.targetPath, targetFile);
    
    if (fs.existsSync(sourcePath)) {
      processFile(sourcePath, targetPath);
    } else {
      console.warn(`Source file ${sourcePath} does not exist, skipping...`);
    }
  }
  
  console.log('Rule conversion completed successfully!');
}

// Run the main function
main(); 